<?php
namespace app;

use app\common\util\ErrorCode;
use app\common\util\Tools;
use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\Response;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * Report or log an exception.
     *
     * @access public
     * @param  \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        if (!$this->isIgnoreReport($exception)) {
            if(request()->isJson()) {
                // 收集异常数据
                $data = [
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                    'msg' => $this->getMessage($exception),
                    'code' => $this->getCode($exception),
                ];
                Tools::writeLog("系统异常：" . var_export($data, true), "runLog/systemError.txt");
            }else{
                parent::report($exception);
            }
        }
    }

    /**
     * @access protected
     * @param  Exception $exception
     * @return Response
     */
    protected function convertExceptionToResponse(Exception $exception)
    {
//        if(request()->isJson()) { // ajax请求
            // 收集异常数据
            $data = ErrorCode::$errorCode["try_error"];
            $data = array_merge($data, [
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'msg' => $this->getMessage($exception)
            ]);
            $response = Response::create($data, 'json');
            if ($exception instanceof HttpException) {
                $statusCode = $exception->getStatusCode();
                $response->header($exception->getHeaders());
            }
            if (!isset($statusCode)) {
                $statusCode = 200;
            }
            $response->code($statusCode);
            return $response;
//        }else{ // 正常http请求，是返回页面数据了
//            return parent::convertExceptionToResponse($exception);
//        }
    }
}
